"""
Copyright 2012 Wieser Dietmar, Margit Mutschlechner.

This file is part of Multimedia Social Networking Platform.

Multimedia Social Networking Platform is free software: 
you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Multimedia Social Networking Platform is distributed
in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Multimedia Social Networking Platform.  
If not, see <http://www.gnu.org/licenses/>.

"""

from PyQt4 import QtGui, QtCore
from msnp.gui import GUIHelper, UIText, Resources, MyStyle
from msnp.service import network
from msnp.model import PTPModel
from msnp import gui


class ConfirmWidget(QtGui.QDialog):
    """This class represents a member confirm widget which enables the user to confirm pending memberships.
    
    Parameters:
        __parent: A QWidget object containing the parent frame. Default None.
        __mainLayout: A QVBoxLayout object containing either a ConfirmSplashWidget object, or the item __butClose and either the item __tabWidget or __lblNoMembers.
        __tabWidget: A QTabWidget object containing GroupTab objects.
        __lblNoMembers: A QLabel object.
        __butClose: A QPushButton object connected to the method close().
    """
    def __init__(self, parent=None):
        """The init-method."""
        QtGui.QWidget.__init__(self, parent)
        self.__tabWidget = None
#        self.setWindowIcon(QtGui.QIcon(Resources.))
        self.setFixedSize(400, 400)
        self.setWindowIcon(QtGui.QIcon(Resources.IMAGE_CONFIRM_MEMBERS))
        self.__mainLayout = QtGui.QVBoxLayout()
#        self.setModal(True)
        self.setLayout(self.__mainLayout)
        GUIHelper.centerWidget(self)
        
    def buildConfirmSplashWidget(self):
        """Initializes the item __mainLayout and adds a ConfirmSplashWidget."""
        self.setWindowTitle(UIText.TITLE_PLEASE_WAIT)
        self.__cleanLayout()
        confirmSplashWidget = ConfirmSplashWidget()
        self.__mainLayout.addWidget(confirmSplashWidget)
        self.setFixedSize(350, 450)
        self.repaint()

    def buildConfirmWidget(self, groups):
        """Initializes the item __mainLayout and adds the items __butClose and either the item __tabWidget or __lblNoMembers."""
        self.setWindowTitle(UIText.TITLE_UNCONFIRMED_MEMBERS)
        self.__cleanLayout()
        self.__initButtons()
        if groups != None and len(groups) > 0:
            self.__initTabs()
            for group in groups:
                print "Found group with members to confirm: " + group.getGroupname()
                self.__createTab(group)
            self.__mainLayout.addWidget(self.__tabWidget)
        else:
            self.__noUnconfirmedMembers()
            self.__mainLayout.addWidget(self.__lblNoMembers)
        self.__mainLayout.addWidget(self.__butClose)

    def __cleanLayout(self):
        """Removes all items from the item __mainLayout."""
        import sip
        if self.layout() != None:
            oldLayout = self.layout()
            for i in reversed(range(oldLayout.count())):
                oldLayout.itemAt(i).widget().setParent(None)
            sip.delete(oldLayout)
        self.__mainLayout = QtGui.QVBoxLayout()
        self.setLayout(self.__mainLayout)
        self.__tabWidget = None
        
    def __initTabs(self):
        """Initializes the item __tabWidget."""
        self.__tabWidget = QtGui.QTabWidget(self)
        self.__tabWidget.setTabsClosable(True)

    def __initButtons(self):
        """Initializes the item __butClose."""
        self.__butClose = QtGui.QPushButton(UIText.BUT_CLOSE, self)
        self.__butClose.setFocusPolicy(QtCore.Qt.NoFocus)
        self.__butClose.setIcon(QtGui.QIcon(Resources.IMAGE_BUT_DISCARD))
        self.connect(self.__butClose, QtCore.SIGNAL('clicked()'), self.close)
            
    def __createTab(self, group):
        """Creates a new GroupTab object and adds it to the item __tabWidget."""
        tab = GroupTab(group, self)
        self.__tabWidget.addTab(tab, group.getGroupname())
    
    def __noUnconfirmedMembers(self):
        """Initializes the item __lblNoMembers."""
        self.__lblNoMembers = QtGui.QLabel(UIText.LABEL_NO_MEMBERS_TO_CONFIRM)
        self.__lblNoMembers.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
        self.__lblNoMembers.setFont(MyStyle.getFont13Cursive())

    def closeEvent(self, event):
        """This method is called when the widget closes."""
        gui.GUIController.closeConfirmWidget()
        event.accept()

class ConfirmSplashWidget(QtGui.QWidget):
    """This class represents a member confirm splash widget displayed while waiting for the data to display.
    
    Parameters:
        __parent: A QWidget object containing the parent frame. Default None.
        __mainLayout: A QVBoxLayout object containing the items __lblSplash and __lblLoading.
        __lblSplash: A QLabel object containing the item __movie.
        __lblLoading: A QLabel object.
        __movie: A QMovie object.
    """
    def __init__(self, parent=None):
        """The init-method."""
        QtGui.QWidget.__init__(self, parent)
        self.__mainLayout = QtGui.QVBoxLayout()
        self.__build()
        self.setLayout(self.__mainLayout)
        
    def __build(self): 
        """Initializes the item __mainLayout and adds its contained items."""
        self.__initSplashLabels()
        self.__mainLayout.addWidget(self.__lblSplash)
        self.__mainLayout.addWidget(self.__lblLoading)
        
    def __initSplashLabels(self):
        """Initializes the items __lblSplash, __lblLoading and __movie."""
        #movie container
        self.__lblSplash = QtGui.QLabel()
#        self.__lblSplash.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        self.__lblSplash.setAlignment(QtCore.Qt.AlignCenter)
        #create movie
        self.__movie = QtGui.QMovie(Resources.IMAGE_LOADING, QtCore.QByteArray(), self)
        self.__movie.setCacheMode(QtGui.QMovie.CacheAll)
        self.__movie.setSpeed(100)
        self.__lblSplash.setMovie(self.__movie)
        self.__movie.start()
        self.__lblLoading = QtGui.QLabel(UIText.LABEL_LOADING_MESSAGES)
        self.__lblLoading.setAlignment(QtCore.Qt.AlignHCenter)
        
        
class GroupTab(QtGui.QWidget):
    """This class represents one tab of the confirm widget which displays all users to confirm belonging to the same group.
    
    Parameters:
        __parent: A QWidget object containing the parent frame. Default None.
        __mainLayout: A QVBoxLayout object containing a QScrollArea object, which contains QLabel objects and ConfirmBtn objects.
        __group: A Group object.
    """
    def __init__(self, group, parent=None):
        """The init-method."""
        QtGui.QWidget.__init__(self, parent)
        self.__group = group
        self.__mainLayout = QtGui.QVBoxLayout()
        self.__build()
        self.setLayout(self.__mainLayout)

    def __build(self):
        """Initializes the widget."""
#        self.__mainLayout.setColumnStretch(1, 1)
        scrollarea = QtGui.QScrollArea()
        tabLayout = QtGui.QGridLayout()
        tabLayout.setColumnStretch(0, 1)
        tabLayout.setColumnStretch(1, 1)
        i = 0
        for member in self.__group.getMembers():
            lblMemberName = QtGui.QLabel(member.getName())
            butConfirm = ConfirmBtn(member.getName(), self.__group.getGroupname(), self)
            butConfirm.setFocusPolicy(QtCore.Qt.NoFocus)
            tabLayout.addWidget(lblMemberName, i, 0)
            tabLayout.addWidget(butConfirm, i, 1)
            i += 1
        scrollarea.setFrameShape(QtGui.QFrame.StyledPanel)
        scrollarea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        scrollarea.setLayout(tabLayout)
        self.__mainLayout.addWidget(scrollarea)
            
class ConfirmBtn(QtGui.QPushButton):
    """This class represents the button of a GroupTab object that confirms a member.
    
    Parameters:
        __parent: A QWidget object containing the parent frame. Default None.
        __membername: A String representing the name of the member.
        __groupname: A String representing the name of the group.
    """
    def __init__(self, membername, groupname, parent=None):
        """The init-method."""
        QtGui.QPushButton.__init__(self, parent)
        self.__membername = membername
        self.__groupname = groupname
        self.connect(self, QtCore.SIGNAL('clicked()'), self.__confirmMember)
        self.setText(UIText.BUT_CONFIRM_MEMBER)
        
    def __confirmMember(self):
        """This method is connected to the QPushButton and initializes a change membership status procedure."""
        myName = network.NetworkController.getMySelf().getMyIdentity().getName()
        network.NetworkController.changeMemberStatus(self.__membername, self.__groupname, myName, PTPModel.MemberStatus.ACTIVE)
        self.setEnabled(False)
